package com.dny.asmtop.op;

import com.dny.asmtop.CB;
import com.dny.asmtop.Command;
import com.dny.asmtop.MethodContext;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.commons.GeneratorAdapter;

import java.util.Objects;

/**
 * Created by jlutt on 2018-01-17.
 * 获取参数的length，用于集合类操作
 * @author jlutt
 */
public class CommandLength implements Command {

  private Command argument;

  public CommandLength(Command argument) {
    this.argument = argument;
  }

  @Override
  public Type type(MethodContext context) {
    return Type.INT_TYPE;
  }

  @Override
  public Type generator(MethodContext context) {
    GeneratorAdapter g = context.getGeneratorAdapter();

    if (argument.type(context).getSort() == Type.ARRAY) {
      argument.generator(context);
      g.arrayLength();
    } else if (argument.type(context).getSort() == Type.OBJECT) {
      CB.call(argument, "size").generator(context);
    }

    return Type.INT_TYPE;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CommandLength that = (CommandLength) o;
    return Objects.equals(argument, that.argument);
  }

  @Override
  public int hashCode() {

    return Objects.hash(argument);
  }
}
